package com.jijia.webbase.websocket;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.jijia.webbase.config.security.SaveLoginUser;
import com.jijia.webbase.utils.ThreadLocalUtil;
import com.jijia.webbase.utils.WebSocketUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class myWebSocketHandler implements WebSocketHandler {

    private ConcurrentHashMap<String, WebSocketSession> SESSIONS = new ConcurrentHashMap<>();
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.debug("session URL={}",session.getUri());

        String[] s = session.getUri().toString().split("\\?")[1].split("&");

        HashMap<String,String> map = new HashMap<>();

        SaveLoginUser user = (SaveLoginUser)ThreadLocalUtil.get().get("user");
        String userName = user.getUser().getUserName();
        WebSocketSession oldSession = SESSIONS.put(userName, session);
        //如果有旧session，则关闭旧session
        if(oldSession!=null){
            try {
                oldSession.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        log.debug("查询字符串={}", Arrays.toString(s));
        log.debug("拼接字符串={}",String.join("&",s));
        log.debug("websocket连接成功！");
        log.debug("欢迎"+userName+"加入聊天室");
        SESSIONS.forEach((k,v)->{
            try {
                ChatMessage chatMessage = new ChatMessage();
                chatMessage.setContent("欢迎"+userName+"加入聊天室");
                chatMessage.setSender("system");
                chatMessage.setReceiver("all");
                chatMessage.setTimestamp(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                v.sendMessage(new TextMessage(JSONUtil.toJsonStr(chatMessage)));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        log.debug("websocket收到消息："+message.getPayload());
        ChatMessage chatMessage = JSONUtil.toBean(message.getPayload().toString(), ChatMessage.class);
        if (chatMessage.getReceiver().equals("all")){
            SESSIONS.forEach((k,v)->{
                try {
                    v.sendMessage(new TextMessage(JSONUtil.toJsonStr(chatMessage)));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }else {
            try {
                SESSIONS.get(chatMessage.getReceiver()).sendMessage(new TextMessage(JSONUtil.toJsonStr(chatMessage)));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.debug("websocket发生错误："+exception);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        log.debug("websocket连接关闭！");
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
